package org.devocean.groupbuying.utils;

import org.apache.tiles.AttributeContext;
import org.apache.tiles.context.TilesRequestContext;
import org.apache.tiles.preparer.ViewPreparer;
import org.devocean.groupbuying.domain.Customer;
import org.devocean.groupbuying.service.CustomerService;
import org.devocean.groupbuying.service.MenuService;
import org.devocean.groupbuying.service.PlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Component;

@Component
public class MenuPreparer implements ViewPreparer {

	@Autowired
	private CustomerService customerService;

	@Autowired
	private MenuService menuService;
	
	@Autowired
	private PlanService planService;

	public void execute(TilesRequestContext requestContext,
			AttributeContext context) {
		String lang = null;
		try {
			lang = requestContext
					.getRequestScope()
					.get("org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE")
					.toString();
		} catch (Exception e) {
			// TODO: handle exception
		}
		

		SecurityContext sc = (SecurityContext) requestContext.getSessionScope()
				.get("SPRING_SECURITY_CONTEXT");

		if (sc != null) {
			Customer customer = customerService.getCustomerById(Integer.valueOf(sc
					.getAuthentication().getName()));
			
			requestContext.getRequestScope().put(
					"user",customer.getUserName().split("@")[0]
					);
		}

		requestContext.getRequestScope().put("menus",
				menuService.getAllMenus(lang));
		requestContext.getRequestScope().put("members", 
				customerService.countCustomers());
		requestContext.getRequestScope().put("countplans",planService.countPlans() );
	}
}
